#include "../include/employee_handler.h"
#include "../include/db_manager.h"
#include <jsoncpp/json/json.h>
#include <iostream>
#include <sstream>

std::string EmployeeHandler::getAllEmployees() {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "SELECT * FROM employees ORDER BY Employee_id";
    auto results = db.executeSelectQuery(query);
    
    Json::Value response;
    response["success"] = true;
    response["data"] = Json::Value(Json::arrayValue);
    
    for (const auto& row : results) {
        Json::Value employee;
        employee["id"] = row.at("Employee_id");
        employee["name"] = row.at("Ename");
        employee["department_id"] = row.at("Dno");
        employee["gender"] = row.at("Ssex");
        employee["age"] = row.at("Sage");
        employee["phone"] = row.at("Phone_number");
        employee["hire_year"] = row.at("Hire_time");
        employee["status"] = row.at("Employment_status");
        
        response["data"].append(employee);
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string EmployeeHandler::getEmployeeById(const std::string& id) {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "SELECT * FROM employees WHERE Employee_id = '" + db.escapeString(id) + "'";
    auto results = db.executeSelectQuery(query);//结果集
    
    Json::Value response;
    if (results.empty()) {
        response["success"] = false;
        response["message"] = "员工不存在";
    } else {
        response["success"] = true;
        const auto& row = results[0];
        
        Json::Value employee;
        //获取字段内容
        employee["id"] = row.at("Employee_id");
        employee["name"] = row.at("Ename");
        employee["department_id"] = row.at("Dno");
        employee["gender"] = row.at("Ssex");
        employee["age"] = row.at("Sage");
        employee["phone"] = row.at("Phone_number");
        employee["hire_year"] = row.at("Hire_time");
        employee["status"] = row.at("Employment_status");
        
        response["data"] = employee;
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string EmployeeHandler::addEmployee(const std::string& data) {
    Json::Value request_data;
    Json::Reader reader;
    
    if (!reader.parse(data, request_data)) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "数据格式错误";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = "INSERT INTO employees (Employee_id, Ename, Dno, Ssex, Sage, Phone_number, Hire_time, Employment_status) VALUES ('" +
                       db.escapeString(request_data["id"].asString()) + "', '" +
                       db.escapeString(request_data["name"].asString()) + "', '" +
                       db.escapeString(request_data["department_id"].asString()) + "', '" +
                       db.escapeString(request_data["gender"].asString()) + "', " +
                       request_data["age"].asString() + ", '" +
                       db.escapeString(request_data["phone"].asString()) + "', " +
                       request_data["hire_year"].asString() + ", '" +
                       db.escapeString(request_data["status"].asString()) + "')";
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "员工添加成功";
    } else {
        response["success"] = false;
        response["message"] = "员工添加失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string EmployeeHandler::updateEmployee(const std::string& id, const std::string& data) {
    Json::Value request_data;
    Json::Reader reader;
    
    if (!reader.parse(data, request_data)) {
        Json::Value response;
        response["success"] = false;
        response["message"] = "数据格式错误";
        Json::FastWriter writer;
        return writer.write(response);
    }
    
    DBManager& db = DBManager::getInstance();
    
    std::string query = std::string("UPDATE employees SET ") +
                       "Ename = '" + db.escapeString(request_data["name"].asString()) + "', " +
                       "Dno = '" + db.escapeString(request_data["department_id"].asString()) + "', " +
                       "Ssex = '" + db.escapeString(request_data["gender"].asString()) + "', " +
                       "Sage = " + request_data["age"].asString() + ", " +
                       "Phone_number = '" + db.escapeString(request_data["phone"].asString()) + "', " +
                       "Hire_time = " + request_data["hire_year"].asString() + ", " +
                       "Employment_status = '" + db.escapeString(request_data["status"].asString()) + "' " +
                       "WHERE Employee_id = '" + db.escapeString(id) + "'";
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "员工信息更新成功";
    } else {
        response["success"] = false;
        response["message"] = "员工信息更新失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string EmployeeHandler::deleteEmployee(const std::string& id) {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "DELETE FROM employees WHERE Employee_id = '" + db.escapeString(id) + "'";
    
    Json::Value response;
    if (db.executeQuery(query)) {
        response["success"] = true;
        response["message"] = "员工删除成功";
    } else {
        response["success"] = false;
        response["message"] = "员工删除失败";
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string EmployeeHandler::getEmployeeStatistics() {
    DBManager& db = DBManager::getInstance();
    
    // 总员工数
    auto total_results = db.executeSelectQuery("SELECT COUNT(*) as total FROM employees");
    int total_employees = total_results.empty() ? 0 : std::stoi(total_results[0].at("total"));
    
    // 在职员工数
    auto active_results = db.executeSelectQuery("SELECT COUNT(*) as active FROM employees WHERE Employment_status = '在职'");
    int active_employees = active_results.empty() ? 0 : std::stoi(active_results[0].at("active"));
    
    // 按部门统计
    auto dept_results = db.executeSelectQuery("SELECT Dno, COUNT(*) as count FROM employees GROUP BY Dno");
    
    Json::Value response;
    response["success"] = true;
    response["total_employees"] = total_employees;
    response["active_employees"] = active_employees;
    response["department_stats"] = Json::Value(Json::arrayValue);
    
    for (const auto& row : dept_results) {
        Json::Value dept_stat;
        dept_stat["department_id"] = row.at("Dno");
        dept_stat["count"] = std::stoi(row.at("count"));
        response["department_stats"].append(dept_stat);
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}

std::string EmployeeHandler::getEmployeesByDepartment(const std::string& department_id) {
    DBManager& db = DBManager::getInstance();
    
    std::string query = "SELECT * FROM employees WHERE Dno = '" + db.escapeString(department_id) + "' ORDER BY Employee_id";
    auto results = db.executeSelectQuery(query);
    
    Json::Value response;
    response["success"] = true;
    response["data"] = Json::Value(Json::arrayValue);
    
    for (const auto& row : results) {
        Json::Value employee;
        employee["id"] = row.at("Employee_id");
        employee["name"] = row.at("Ename");
        employee["department_id"] = row.at("Dno");
        employee["gender"] = row.at("Ssex");
        employee["age"] = row.at("Sage");
        employee["phone"] = row.at("Phone_number");
        employee["hire_year"] = row.at("Hire_time");
        employee["status"] = row.at("Employment_status");
        
        response["data"].append(employee);
    }
    
    Json::FastWriter writer;
    return writer.write(response);
}
